package com.xiaohe.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xiaohe.common.to.es.SkuEsModel;
import com.xiaohe.common.utils.R;
import com.xiaohe.gulimall.search.config.GulimallElasticSearchConfig;
import com.xiaohe.gulimall.search.constant.EsConstant;
import com.xiaohe.gulimall.search.fegin.ProductFeignService;
import com.xiaohe.gulimall.search.service.MallSearchService;
import com.xiaohe.gulimall.search.vo.AttrResponseVo;
import com.xiaohe.gulimall.search.vo.SearchParam;
import com.xiaohe.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //1、准备检索请求
        SearchResult result = null;
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            //2、执行检索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);


            //3、分析响应数据，封装成我们想要的数据
            result = buildSearchResult(searchResponse, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建结果数据
     *
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highTitle = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highTitle);
                }
                esModels.add(skuEsModel);
            }
        }
        //封装查询到的所有商品
        result.setProduct(esModels);

        Aggregations aggregations = searchResponse.getAggregations();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            //分类id
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //分类名称
            Aggregations bucketAggregations = bucket.getAggregations();
            ParsedStringTerms catalog_name_agg = bucketAggregations.get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVoList.add(catalogVo);
        }
        result.setCatalogVos(catalogVoList);

        //封装品牌信息
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();

        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            long brandId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVoList.add(brandVo);
        }
        result.setBrandVos(brandVoList);
        //封装查询到的所有属性信息
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            //属性名
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            //属性所有值
            List<String> attrValueList = new ArrayList<>();
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            for (Terms.Bucket attr_value_aggBucket : attr_value_agg.getBuckets()) {
                String keyAsString = attr_value_aggBucket.getKeyAsString();
                attrValueList.add(keyAsString);
            }
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValueList);
            attrVoList.add(attrVo);
        }
        //封装属性信息
        result.setAttrVos(attrVoList);
//
        Integer pageNum = param.getPageNum();
        //分页信息
        result.setPageNum(pageNum);
        //总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //分页信息 总页码计算 11/2 =5...1
        Integer totalSize = EsConstant.PRODUCT_SIZE;
        int totalPages = (int) total % totalSize == 0 ? (int) total / totalSize : ((int) total / totalSize + 1);
        //总页码
        result.setTotalPage(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i =1;i<=totalPages;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //6、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = (AttrResponseVo) r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }
        return result;
    }

    //准备检索请求
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建DSL语句的
        /**
         * 模糊匹配（过滤）按照属性、分类、品牌、价格区间、库存
         */
        //1、构建boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1must
        String keyword = param.getKeyword();//获取是否传入查询条件
        if (StringUtils.isNotEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyword));
        }
        //1.2、bool-query
        //按照三级分类id查询
        Long catalog3Id = param.getCatalog3Id();//三级分类id
        if (catalog3Id != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", catalog3Id));
        }
        //1.2 bool-query
        List<Long> brandId = param.getBrandId();
        if (brandId != null && brandId.size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("catalogId", brandId));
        }


        //1.2 按照是否有库存
        Integer hasStock = param.getHasStock();//0无库存
        if(hasStock !=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock", hasStock == 1));
        }

        //1.2 按照价格区间进行检索
        //1_500/_500/500_
        String skuPrice = param.getSkuPrice();
        if (StringUtils.isNotEmpty(skuPrice)) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] str = skuPrice.split("_");
            if (str.length == 2) {
                rangeQuery.gte(str[0]);
                rangeQuery.lte(str[1]);
            } else if (str.length == 1) {
                if (skuPrice.startsWith("_")) {
                    rangeQuery.lte(str[0]);
                }
                if (skuPrice.endsWith("_")) {
                    rangeQuery.gte(str[0]);
                }
                boolQuery.filter(rangeQuery);
            }
        }
        //1.2、按照属性进行查询
        List<String> attrs = param.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            for (String attr : attrs) {
                BoolQueryBuilder nestBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");//检索这个属性用的值
                nestBoolQuery.must(QueryBuilders.termsQuery("attrs.attrId", attrId));
                nestBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        sourceBuilder.query(boolQuery);
        /**
         * 排序 分页 高亮
         */
        //2.1排序
        String sort = param.getSort();
        if (StringUtils.isNotEmpty(sort)) {
            String[] str = sort.split("_");
            SortOrder order = str[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(str[0], order);
        }
        //分页 pageSize：5
        //pageNum 1 from 0  size 5
        //pageNum 2 from 5   size 5
        //from =(pageNum-1)*pageSize
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_SIZE);
        //高亮
        if (StringUtils.isNotEmpty(keyword)) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle")
                    .preTags("<b style='color:red'>")
                    .postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }


        /**
         * 聚和分析
         */
        //品牌聚和
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId");
        brand_agg.size(50);
        //品牌聚和的子聚和 名字
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
        brand_name_agg.field("brandName");
        brand_name_agg.size(1);
        brand_agg.subAggregation(brand_name_agg);
        //品牌聚和的子聚和 图片
        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg");
        brand_img_agg.field("brandImg");
        brand_img_agg.size(1);
        brand_agg.subAggregation(brand_img_agg);
        sourceBuilder.aggregation(brand_agg);
        //分类聚和catalog_agg
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //属性聚和
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        attr_id_agg.subAggregation(attr_name_agg);

        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50);
        attr_id_agg.subAggregation(attr_value_agg);
        nested.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(nested);


        //System.out.println("----->DSL语句为:" + sourceBuilder.toString());

        /**
         * 聚和分析
         */
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
